<?php

namespace app\index\service;

use app\common\model\Area;
use app\common\model\Member;
use app\index\model\UM as UM;

/**
 * Class LocationCityService
 * @package app\index\service
 */
class LocationCityService
{

    /**
     * 保存定位城市
     * @param UM $user
     * @param array $params
     */
    public function add(UM $user, array $params): void
    {
        $cityId = $params['cityId'];
        if (!is_id($cityId)) {
            return;
        }

        $city = Area::where('id', $cityId)
            ->where('status', 0)
            ->find();

        if (is_id($city->province) && !is_id($city->city)) {

            // 更新当前定位
            $this->updateLocationCity($user, $city);
        }
    }

    /**
     * 更新当前定位城市
     * @param Member $member
     * @param Area $city
     * @return void
     */
    public function updateLocationCity(Member $member, Area $city)
    {
        // 只保存最新值，不保存历史定位城市
        $member->provinceId = $city->province;
        $member->cityId = $city->id;
        $member->save();
    }

    public function read(UM $user, $id): ?Area
    {

        if (!is_id($id) || !is_id($user->cityId)) {
            return null;
        }

        return Area::where('id', $user->cityId)
            ->where('status', 0)
            ->with(['parent'])
            ->find();
    }
}
